package com.gf.common.ehcache;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;

/**
 * ehcache实现的cache
 * Hibernate的二级缓存
 * 
 * @author Colonel
 *
 */
public class EhcacheWrapper implements CacheWrapper {
	private static final Log LOGGER = LogFactory.getLog(EhcacheWrapper.class);
	//在applicationContext-common.xml已配置完成
	private Cache cache;
	
	@Override
	public void add(String key, Object value) {
		Element element = new Element(key, value);
		element.setVersion(element.getCreationTime());
		cache.put(element);
	}

	@Override
	public void add(String key, Object value, long expiry) {
		int timeToLiveSeconds = (int) (expiry /1000);
		Element element = new Element(key, value);
		element.setEternal(false);
		element.setTimeToLive(timeToLiveSeconds);
		element.setVersion(element.getCreationTime());
		cache.put(element);
	}

	@Override
	public boolean delete(String key) {
		return cache.remove(key);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	@Deprecated
	public void deleteStartWith(String keyPrefix) {
		List<String> keys = cache.getKeys();
		if(keys == null || keys.isEmpty()) {
			return;
		}
 		for(String key : keys) {
 			if(key.startsWith(keyPrefix)) {
 				try {
 					cache.remove(key);
 				} catch (Exception e) {
 					LOGGER.warn("删除key:"+key+"对应缓存失败",e);
				}
 			}
 		}
	}

	@Override
	public void removeAll() {
		cache.removeAll();
	}

	@Override
	public Object get(String key) {
		Element element = cache.get(key);
		if(element != null) {
			return element.getObjectValue();
		} else {
			return null;
		}
	}

	@Override
	public boolean keyExists(String key) {
		return cache.isKeyInCache(key);
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}
}
